package com.shjy.driver.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.os.Message;

import com.shjy.driver.R;
import com.shjy.driver.delegate.BaseWebviewDelegate;
import com.shjy.driver.util.AppUtil;
import com.shjy.driver.util.Const;
import com.shjy.driver.util.HttpFileUpTool;
import com.shjy.driver.util.HttpFileUtil;

import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends AppCompatActivity {

    private WebView mWebView;

    private String mCameraFilePath = null;
    private ValueCallback mUploadMessage;
    private final static int FILECHOOSER_RESULTCODE = 1;

    private static final String SD_CARD_TEMP_PHOTO_PATH = "/sdcard/xxgistemp.jpg";

    public String fileFullName;//照相后的照片的全整路径
    private boolean fromTakePhoto; //是否是从摄像界面返回的webview

    private static Handler viewHandler = null;

    public static final int CHECK_UPDATE = 1;
    public static final int QUERY_UPDATE = 2;
    public static final int METHOD_CALL = 3;
    public static final int SUBMIT_DONE = 4;

    public String urlparafull;//url路径
    public String fileElementIdfull;//fileElementId全局变量

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == fileFullName)
                return;
            Uri result = intent == null || resultCode != Activity.RESULT_OK ? null
                    : intent.getData();

            if (result == null && intent == null
                    && resultCode == Activity.RESULT_OK) {
                System.out.println(fileFullName);
                saveImage(fileFullName,true);
            }

            fileFullName = null;
        }
    }

    public void saveImage(final String image,final boolean showMessage){
    	/*final ProgressDialog dialog = ProgressDialog.show(context, context.getResources().getString(
				R.string.doing), context.getResources().getString(
						R.string.submitting), true,true);*/


        new Thread() {
            public void run() {
                try {

                    Map<String, String> params = new HashMap<String, String>();
                    Map<String, File> files = new HashMap<String, File>();
                    File file = new File(SD_CARD_TEMP_PHOTO_PATH);
                    if(image != null && image.length()>0){
                        Uri u = FileProvider.getUriForFile(
                                LoginActivity.this,
                                "com.shjy.driver.provider",
                                new File(image));

                        InputStream fileInputStream=LoginActivity.this.getContentResolver().openInputStream(u);

                        OutputStream os = new FileOutputStream(file);
                        int bytesRead = 0;
                        byte[] buffer = new byte[1024];
                        while ((bytesRead = fileInputStream.read(buffer, 0, 1024)) != -1) {
                            os.write(buffer, 0, bytesRead);
                        }
                        os.close();
                        fileInputStream.close();

                        Bitmap bm = BitmapFactory.decodeFile(SD_CARD_TEMP_PHOTO_PATH);

                        bm = AppUtil.zoomBitmap(bm,480,320);

                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));

                        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);

                        bos.flush();

                        bos.close();

                        System.gc();

                        files.put("myphoto.jpg", file);
                    }
                    params.put("guid",java.util.UUID.randomUUID().toString());

                    String url = "";
                    String rtn = HttpFileUtil.sendFormFile(Const.DOMAIN+Const.IMAGE_UPLOAD + "?"+urlparafull,new HashMap<String, String>(), file, fileElementIdfull);

                    //String rtn = HttpFileUpTool.post(Const.DOMAIN+Const.IMAGE_UPLOAD + "?"+urlparafull, params, files);
                    //String rtn = HttpFileUpTool.post("http://218.202.254.248/JDFDAGISAPP/upload", params, files);

                    JSONObject jsonObject = new JSONObject(rtn);
                    Message msg = new Message();
                    msg.what = SUBMIT_DONE;

                    Bundle data = new Bundle();
                    data.putString("billAttachId", rtn);
                    data.putString("fileUrl", jsonObject.getString("fileUrl"));
                    data.putBoolean("msg", showMessage);
                    data.putInt("cid", 1);
                    data.putInt("rid", 1);
                    msg.setData(data);

                    viewHandler.sendMessage(msg);


                } catch (Exception e) {
                    e.printStackTrace();

//                    Message msg = new Message();
//                    msg.what = MainActivity.SUBMIT_DONE;
//
//                    Bundle data = new Bundle();
//                    data.putString("rtn", "{'success': 'false'}");
//                    data.putBoolean("msg", showMessage);
//                    data.putInt("cid", 1);
//                    data.putInt("rid", 1);
//                    msg.setData(data);
//
//                    viewHandler.sendMessage(msg);

                } finally {

                }
            }
        }.start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // layout
        setContentView(R.layout.activity_login);

        // 初始化 WebView
        initWebview();

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        viewHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {

                if(msg.what == SUBMIT_DONE){
                    Bundle data = msg.getData();
                    int cid = data.getInt("cid", -1);
                    int rid = data.getInt("rid", -1);
                    String billAttachId = data.getString("billAttachId");
                    String fileUrl = data.getString("fileUrl");
                    onSubmitDone(billAttachId);
                }
            }
        };

        // 权限设定
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                ) {

            AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
            builder.setMessage("请授予\"交运便捷\"摄像头权限").setNegativeButton("禁止", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            }).setPositiveButton("允许", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                    }
                }
            }).create().show();
        }
    }

    private void onSubmitDone(String rtn){
        mWebView.loadUrl("javascript:submitDone("+rtn+")");
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    private void initWebview() {

        mWebView = (WebView) findViewById(R.id.webview);

        // 优先使用缓存
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        mWebView.getSettings().setDomStorageEnabled(true);

        mWebView.setWebViewClient(new LoginWebViewClient(this));
        mWebView.setWebChromeClient(new LoginWebChromeClient());
        mWebView.addJavascriptInterface(new LoginWebviewDelegate(LoginActivity.this), "delegate");

        mWebView.loadUrl(Const.URL_LOGIN);
    }

    class LoginWebViewClient extends WebViewClient {

        private LoginActivity mLoginActivity;

        public LoginWebViewClient(LoginActivity loginActivity) {
            mLoginActivity = loginActivity;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d("Login", url);
            if (TextUtils.equals(url, Const.URL_HOME)) {
                mLoginActivity.finish();
                return false;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }
    }

    class LoginWebChromeClient extends WebChromeClient {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
            builder.setTitle(null).setMessage(message).setPositiveButton("确定", null);
            builder.setCancelable(false);
            AlertDialog dialog = builder.create();
            dialog.show();
            result.confirm();
            return true;
        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {

            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            LoginActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);

        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            LoginActivity.this.startActivityForResult(
                    Intent.createChooser(i, "File Browser"),
                    FILECHOOSER_RESULTCODE);
        }

        //For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            LoginActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), LoginActivity.FILECHOOSER_RESULTCODE);

        }

        private Intent createDefaultOpenableIntent() {
            // Create and return a chooser with the default OPENABLE
            // actions including the camera, camcorder and sound
            // recorder where available.
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");

            Intent chooser = createChooserIntent(createCameraIntent(),
                    createCamcorderIntent(), createSoundRecorderIntent());
            chooser.putExtra(Intent.EXTRA_INTENT, i);
            return chooser;
        }

        private Intent createChooserIntent(Intent... intents) {
            Intent chooser = new Intent(Intent.ACTION_CHOOSER);
            chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
            chooser.putExtra(Intent.EXTRA_TITLE, "File Chooser");
            return chooser;
        }

        private Intent createCameraIntent() {
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            File externalDataDir = Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
            System.out.println("externalDataDir:" + externalDataDir);
            File cameraDataDir = new File(externalDataDir.getAbsolutePath()
                    + File.separator + "browser-photo");
            cameraDataDir.mkdirs();
            mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator
                    + System.currentTimeMillis() + ".jpg";
            System.out.println("mcamerafilepath:" + mCameraFilePath);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(new File(mCameraFilePath)));

            return cameraIntent;
        }

        private Intent createCamcorderIntent() {
            return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        }

        private Intent createSoundRecorderIntent() {
            return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
        }
    }

    class LoginWebviewDelegate extends BaseWebviewDelegate {

        public LoginWebviewDelegate(Context context) {
            super(context);
        }

        @JavascriptInterface
        public String clickOnAndroid(String urlpara,String fileElementId) {//将被js调用
            fileElementIdfull = fileElementId;
            urlparafull = urlpara;
            takePhoto("testimg" + Math.random()*1000+1 + ".jpg");
            return fileFullName;
        }
    }

    /*
    * 调用摄像头的方法
    */
    public void takePhoto(String filename) {
        try{
            System.out.println("----start to take photo2 ----");
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_MEDIA_TITLE, "TakePhoto");

            //判断是否有SD卡
            String sdDir = null;
            boolean isSDcardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
            if(isSDcardExist) {
                sdDir = Environment.getExternalStorageDirectory().getAbsolutePath();
            } else {
                sdDir = Environment.getRootDirectory().getAbsolutePath();
            }
            //确定相片保存路径
            String targetDir = sdDir + "/" + "webview_camera";
            File file = new File(targetDir);
            if (!file.exists()) {
                file.mkdirs();
            }
            fileFullName = targetDir + "/" + filename;
            System.out.println("----taking photo fileFullName: " + fileFullName);
            //初始化并调用摄像头
            Uri photoOutputUri = FileProvider.getUriForFile(
                    this.getApplication(),
                    "com.shjy.driver.provider",
                    new File(fileFullName));
            intent.putExtra(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoOutputUri);
            startActivityForResult(intent, 1);
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
